/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkRtsp/MkRtspPlayer.h"
#include <MkUtil/MkLog.h>
#include "MkEvent/MkEvent.h"
#include "MkUtil/MkThread.h"
#include "MkRtsp/MkRtspSubSession.h"
#include "MkEvent/MkTimer.h"
#include "MkEvent/MkEventPool.h"
#include "MkRtp/MkRtpServerPool.h"
#include <signal.h>

int main(int argc, char** argv)
{
#ifdef _WIN32
    WSADATA WSAData;
    WSAStartup(0x101, &WSAData);
#else
    signal(SIGPIPE, SIG_IGN);  //ignore sigpipe
#endif
    //if (argc < 2) {
    //    printf("useage:%s rtspUrl\n", argv[0]);
    //    return 0;
    //}
    //    MkString RtspUrl = argv[1];
    MkString RtspUrl = "rtsp://admin:chaigec123@192.168.101.64:554/h265/ch1/main/av_stream";
    //MkString RtspUrl = "rtsp://admin:zfswjs5g.com@192.168.2.254/h264/ch34/main/av_stream";
    //MkString RtspUrl = "rtsp://admin:zfswjs5g.com@192.168.2.209/h264/ch1/main/av_stream";
    FILE *fp = fopen("rtsp.dat", "wb");
    MkLogInitLevel("TestTcpServer", TO_SCREEN);
    MkLogChangeLevel(LOG_DEBUG);
    CMkEventPool Pool;
    CMkTimer  Timer;
    CMkTimer* pTimer = &Timer;
    Pool.Start(1);
    Timer.StartTimerThread();
    CMkRtpServerPool *pRtpPool = new CMkRtpServerPool(&Pool, &Timer);
    pRtpPool->Start();
    CMkRtspPlayer *pPlayer = new CMkRtspPlayer(Pool.GetFreeEvent(), &Timer, pRtpPool->GetVecRtpUdpServer(), [pTimer](CMkTcpClient *pClient)
    {
        MkDebugLog("player removed\n");
        pTimer->LoopBreak();
        MkDelete(pClient);
        return NoneError;
    });

    pPlayer->Play(RtspUrl, TRUE, [](CMkMediaSource* pMediaSource, Uint32 ErrorCode) {
        return NoneError;
    }, [fp, pPlayer](const MkEsPacket& EsPacket, const CMkVideoParam& VideoParam, const CMkAudioParam& AudioParam) {
        if (MkCodecCavs > EsPacket.CodecType) {
            MkListBuffer::const_iterator it = EsPacket.BufferList.GetBufferList().begin();
            for (; it != EsPacket.BufferList.GetBufferList().end(); it++) {
                fwrite(&NaluStartCode, 1, 4, fp);
                fwrite(it->GetBuffer(), 1, it->GetLength(), fp);
            }
        }
        return NoneError;
    });
    while (1) {
        char tmp = getchar();
        if ('q' == tmp) {
            break;
        } else if ('s' == tmp) {
            pPlayer->StopMediaSource();
            CMkThread::ThreadSleep(2000);
            break;
        }
    }
    Timer.StopTimerThread();
    pRtpPool->Stop();
    Pool.Stop();
#ifdef _WIN32
    WSACleanup();
#endif
    return 0;
}




